package com.web.new12306.util;

import java.io.DataInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.swing.JOptionPane;
/**

 * @author 苗宇
 *
 */
public final class FileUtil {
	public static class Position {
		int begin;
		int end;

		Position(int begin, int end) {//定位
			this.begin = begin;
			this.end = end;
		}
	}

	public static byte[] readBody(HttpServletRequest request) throws IOException {
		int formDataLength = request.getContentLength();//文件的大小
		//DataInputStream和DataOutputStream都是Java中输入输出流的装饰类
		DataInputStream dataStream = new DataInputStream(request.getInputStream());
		byte body[] = new byte[formDataLength];
		int totalBytes = 0;
		while (totalBytes < formDataLength) {
			int bytes = dataStream.read(body, totalBytes, formDataLength);
			totalBytes += bytes;
		}
		return body;
	}

	public static Position getFilePosition(HttpServletRequest request, String textBody) throws IOException {

		String contentType = request.getContentType();
		String boundaryText = contentType.substring(contentType.lastIndexOf("=") + 1, contentType.length());
		int pos = textBody.indexOf("filename=\"");
		pos = textBody.indexOf("\n", pos) + 1;
		pos = textBody.indexOf("\n", pos) + 1;
		pos = textBody.indexOf("\n", pos) + 1;
		int boundaryLoc = textBody.indexOf(boundaryText, pos) - 4;
		int begin = ((textBody.substring(0, pos)).getBytes("ISO-8859-1")).length;
		int end = ((textBody.substring(0, boundaryLoc)).getBytes("ISO-8859-1")).length;

		return new Position(begin, end);
	}

	public static String getFilename(String reqBody) {
		String filename = reqBody.substring(reqBody.indexOf("filename=\"") + 10);
		filename = filename.substring(0, filename.indexOf("\n"));
		filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.indexOf("\""));
		return filename;
	}

	public static void writeTo(FileOutputStream fileOutputStream, byte[] body, Position p) throws FileNotFoundException, IOException {
		if(p.end - p.begin<8192) {
		fileOutputStream.write(body, p.begin, (p.end - p.begin));//从body中读取p.begin--(p.end - p.begin)长的数据
		fileOutputStream.flush();
		fileOutputStream.close();}
		else {
			JOptionPane.showMessageDialog(null, "图片过大", "出错啦",JOptionPane.ERROR_MESSAGE);
		}

}
}